const { pool } = require('../config/database');

// 保存表单（新增或更新）
// 入参：{ formId?: string, title: string, items: any }
// 返回：{ code: 0, data: { formId } }
const saveForm = async (req, res) => {
  try {
    const { formId, title = '', items } = req.body || {};
    if (!items) {
      return res.status(200).json({ code: 1, message: '缺少表单内容' });
    }

    const content = JSON.stringify({ title, items });
    const creatorId = req.user?.userId || null;

    if (formId) {
      await pool.execute(
        'UPDATE forms SET title = ?, content = ?, updated_at = CURRENT_TIMESTAMP WHERE form_id = ?',
        [title, content, formId]
      );
      return res.status(200).json({ code: 0, message: '更新成功', data: { formId } });
    }

    // 生成新的 form_id
    const newFormId = Math.random().toString(36).slice(2, 10);
    await pool.execute(
      'INSERT INTO forms (form_id, title, content, creator_id) VALUES (?, ?, ?, ?)',
      [newFormId, title, content, creatorId]
    );
    return res.status(200).json({ code: 0, message: '保存成功', data: { formId: newFormId } });
  } catch (error) {
    console.error('保存表单错误:', error);
    return res.status(500).json({ code: 1, message: '服务器内部错误' });
  }
};

// 问卷详情
// GET /api/forms/:formId -> { code: 0, data: { formId, title, items } }
const getFormDetail = async (req, res) => {
  try {
    const { formId } = req.params;
    const [rows] = await pool.execute(
      'SELECT form_id, title, content FROM forms WHERE form_id = ? LIMIT 1',
      [formId]
    );
    if (!rows || rows.length === 0) {
      return res.status(200).json({ code: 1, message: '表单不存在' });
    }
    const row = rows[0];
    let parsed;
    try {
      parsed = JSON.parse(row.content);
    } catch (_) {
      parsed = { title: row.title || '', items: [] };
    }
    return res.status(200).json({
      code: 0,
      data: { formId: row.form_id, title: parsed.title ?? row.title ?? '', items: parsed.items ?? [] }
    });
  } catch (error) {
    console.error('获取表单详情错误:', error);
    return res.status(500).json({ code: 1, message: '服务器内部错误' });
  }
};

module.exports = { saveForm, getFormDetail };


